import os
import sys

BUILD = 'release'
# BUILD = 'debug'

DEVICE    = ' -mcpu=cortex-a7 -mfpu=vfpv4 -ffunction-sections -fdata-sections'
ASFLAGS   = DEVICE + ' -c -x assembler-with-cpp'
CCFLAGS   = DEVICE + ' -Wall'
CXXFLAGS  = CCFLAGS
LINKFLAGS = DEVICE + ' -nostartfiles -Wl,--gc-sections,-Map=sunxi-spl.map,-cref -T./link.ld'

if BUILD == 'debug':
    CCFLAGS += ' -O0 -gdwarf-2'
    ASFLAGS += ' -gdwarf-2'
else:
    CCFLAGS += ' -O2'

env = Environment(
    tools = ['mingw'],
    AS = 'arm-none-eabi-gcc', ASFLAGS = ASFLAGS,
    CC = 'arm-none-eabi-gcc', CCFLAGS = CCFLAGS,
    CXX = 'arm-none-eabi-gcc', CXXFLAGS = CXXFLAGS,
    AR = 'arm-none-eabi-ar',  ARFLAGS = '-rc',
    LINK = 'arm-none-eabi-g++', LINKFLAGS = LINKFLAGS
)

EXEC_PATH   = r'/opt/mingw/bin' 

if os.getenv('RTT_EXEC_PATH'):
    EXEC_PATH = os.getenv('RTT_EXEC_PATH')

env.PrependENVPath('PATH', EXEC_PATH)

src  = Glob('src/*.c')
src += Glob('src/*.S')

env.Program('sunxi-spl.elf', src, CPPPATH='src')

env.AddPostAction('sunxi-spl.elf', 'arm-none-eabi-objdump -D -S $TARGET > sunxi-spl.asm\n')
env.AddPostAction('sunxi-spl.elf', 'arm-none-eabi-objcopy -O binary $TARGET sunxi-spl.bin\n')
env.AddPostAction('sunxi-spl.elf', 'arm-none-eabi-size $TARGET\n')
if sys.platform != 'win32':
    env.AddPostAction('sunxi-spl.elf', 'chmod +x mksunxi/mksunxi')
    env.AddPostAction('sunxi-spl.elf', 'ls -l mksunxi')
    env.AddPostAction('sunxi-spl.elf', './mksunxi/mksunxi sunxi-spl.bin')
else :
    env.AddPostAction('sunxi-spl.elf', '@cmd /c .\\mksunxi\\mksunxi.exe sunxi-spl.bin')
env.Clean('sunxi-spl.elf', './sunxi-spl.bin')
env.Clean('sunxi-spl.elf', './sunxi-spl.asm')
env.Clean('sunxi-spl.elf', './sunxi-spl.map')
